package utils

import (
	//"bytes"

	"io/ioutil"
	"net/http"
	"os"
	"path/filepath"

	"fmt"

	"github.com/gin-gonic/gin"
	// "encoding/json"
	// "archive/tar"
	//
	// "io"
	// "encoding/base64"
	// "path/filepath"
)

// 用户头像路径
var AvatarPath = "asset\\users_avatar_image"

// 图片格式消息储存路径
var MsgImagePath = "asset\\messages_image"

// 保存二进制数据到特定目录
func SaveBinaryDataToDir(data []byte, fileName string) {
	// 使用 filepath.Join 拼接路径
	filePath := filepath.Join(MsgImagePath, fileName)
	err := os.WriteFile(filePath, data, 0644)
	if err != nil {
		fmt.Println("Failed to save binary data:", err)
		return
	}
	fmt.Printf("Binary data saved to %s\n", filePath)
}

func SendImage(c *gin.Context) {
	type requst struct {
		Filename string `json:"filename"`
		Type     int    `json:"Type"`//1头像 2聊天消息
		
	}
	var data requst
    // 将客户端请求体中的 JSON 数据绑定到 data 结构体
    if err := c.BindJSON(&data); err != nil {
        // 若绑定出错，返回 HTTP 400 状态码和错误信息
        c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
        return
    }
	image := data.Filename

	//将文件名保存在请求头，为后续客户端识别文件做准备
	//c.Writer.Header().Set("fileName",iamge)
	// 获取图片路径
    var imagePath string
    if data.Type == 1 {
        imagePath = filepath.Join(AvatarPath, image)
    } else if data.Type == 2 {
        imagePath = filepath.Join(MsgImagePath, image)
    }
	
	if imagePath == "" {
		c.JSON(http.StatusBadRequest, gin.H{"error": "Avatar field is missing or empty"})
		return
	}

	// 读取图片文件
	imageData, err := ioutil.ReadFile(imagePath)
	if err != nil {
		c.JSON(http.StatusNotFound, gin.H{"error": fmt.Sprintf("Image not found: %v", err)})
		return
	}

	// 发送图片数据，去掉手动设置响应头
	c.Data(http.StatusOK, "image", imageData)
}
